/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.heyma.core.security;

import com.icg.entityclassutils.DynamicEntityMap;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.heyma.core.service.IEntityServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 *
 * @author Ruben Q. Huanacuni Cano
 */
@Controller
public class UsuarioController {

    @Autowired
    IEntityServices service;

    @PreAuthorize("hasRole('ROLE_ADMINISTRADOR')")
    @RequestMapping(value = "/formusuario")
    public String formUsuario() {
        return "/usuarios/AdministrarUsuario";
    }

    @PreAuthorize("hasRole('ROLE_ADMINISTRADOR')")
    @RequestMapping(value = "/registrarusuario", method = RequestMethod.POST)
    public String registrarUsuario(Usuario uploadItem) {

        try {
            Map<String, Object> textdata = new HashMap<String, Object>();
            //GetFoto image from upload file            
            if (uploadItem.getUsuario_imagen() != null) {
                byte[] bytes = IOUtils.toByteArray(uploadItem.getUsuario_imagen().getInputStream());
                String usuario_imagen = new sun.misc.BASE64Encoder().encode(bytes);
                textdata.put("usuario_imagen", usuario_imagen);
            }

            textdata.put("usuario", uploadItem.getUsuario());
            textdata.put("passwords", hashMD5Password(uploadItem.getPasswords()));
            textdata.put("rol_id", uploadItem.getRol_id());
            textdata.put("active", uploadItem.getActive());
            textdata.put("usuario_nombre", uploadItem.getUsuario_nombre());
            textdata.put("usuario_apellido", uploadItem.getUsuario_apellido());
            textdata.put("usuario_direccion", uploadItem.getUsuario_direccion());
            textdata.put("usuario_telefono", uploadItem.getUsuario_telefono());
            textdata.put("usuario_celular", uploadItem.getUsuario_celular());
            textdata.put("usuario_email", uploadItem.getUsuario_email());
            textdata.put("usuario_posicion", uploadItem.getUsuario_posicion());

            Map<String, String> tableMap = service.tableColumnsMap("sys", "usuario");
            Map<String, Object> insertable = DynamicEntityMap.parseInputMap(textdata, tableMap);

            service.persist(insertable, "sys", "usuario");

        } catch (Exception e) {
            e.printStackTrace();
        }
        //return "/licitaciones/RegistrarCaso";
        return "redirect:/formusuario";
    }

    @PreAuthorize("isAuthenticated()")
    @RequestMapping(value = "/formcontrasenia")
    public String password() {
        return "/seguridad/ChangePassword";
    }

    @PreAuthorize("isAuthenticated()")
    @RequestMapping(value = "/changepassword")
    public String changePassword(Model model, @RequestParam String usuario, @RequestParam String old_password, @RequestParam String new_password) {
        try {
            Map<String, Object> er = service.getExistObject("sys", "usuario", "usuario", usuario);
            if (er.get("passwords").equals(hashMD5Password(old_password))) {
                er.put("passwords", this.hashMD5Password(new_password));
                service.persist(er, "sys", "usuario");
                model.addAttribute("mensaje", "true");
            } else {
                model.addAttribute("mensaje", "false");
            }
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
            model.addAttribute("mensaje", "false");
        }
        return "/seguridad/ChangePassword";
    }

    public String hashMD5Password(String password) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(password.getBytes());

        byte byteData[] = md.digest();
        //convert the byte to hex format method 1
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < byteData.length; i++) {
            sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }

        return sb.toString();
    }
}
